package com.mvd.app.activity;


import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac_wenzhou.An_Huan_HomeActivity;
import com.mvd.app.adapter.ContentAdapter2;
import com.mvd.app.api.ApiConfig;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.Constants;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.FileUtils;
import com.mvd.app.commons.JsonUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.SystemUtil;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.An_Huan_Model;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.HuanBaoModel;
import com.mvd.app.model.OtherWaiJianPhotoModel;
import com.mvd.app.model.OutPhotoItem;
import com.mvd.app.model.PhotoTypeModel;
import com.mvd.app.model.TypeModel;
import com.mvd.app.model.WaiJianItemModel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.iwgang.countuptime.CountupView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.mvd.app.application.BaseApplication.HUANBAO_PHOTO_PREVIEW_LISTS;
import static com.mvd.app.application.BaseApplication.WAIJIAN_PHOTO_PREVIEW_LISTS;


/**
 *
 */
//外检拍照
public class WaiJianPhotoActivity extends TakePhotoActivity implements AdapterView.OnItemClickListener,
        ApiConfig {
    String tag = "tag";
//    // 相册
//    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
//    private static final int PICK_IMAGE_ACTIVITY_REQUEST_CODE = 200;
//    private static String picFileFullName;

    @BindView(R.id.ac_waijian_photo_listview)
    ListView acWaijianPhotoListview;
    @BindView(R.id.ac_waijian_btn_buhege2)
    Button acWaijianBtnBuhege2;
    @BindView(R.id.ac_waijian_btn_wancheng2)
    Button acWaijianBtnWancheng2;
    @BindView(R.id.ac_waijian_btn_other_imags)
    Button acWaijianBtnOtherImages;
    @BindView(R.id.ac_waijian_photo_scrollview)
    ScrollView acWaijianScrollView;
    @BindView(R.id.ac_waijian_tv_jishiqi_time_time)
    TextView acWaijianTvJishiqi;
    @BindView(R.id.ac_waijian_photo_ll_bottom_layout)
    LinearLayout acWaijianPhotoLlBottomLayout;
    @BindView(R.id.ac_waijian_btn_an_photo_take)
    Button acWaijianBtnAnPhotoTake;
    @BindView(R.id.ac_waijian_btn_huan_photo_take)
    Button acWaijianBtnHuanPhotoTake;
    @BindView(R.id.ac_waijian_right_txt)
    TextView acWaijianTv_other_photo;

    private WaiJianPhotoActivity instances = null;
    //    private String ID = null;//检测车辆ID
//    private String carNo = null;//车牌号码
//    private String PlateType = null;//号牌种类类型
//    private String cartype = null;//车辆类型
    private String PHOTO_TYPE = "";//外检拍照的TYPE上传类型
    private String NAME_LOG = "";
    private String PHOTO_TYPE_huan = "";//外检拍照的TYPE上传类型
    private String waijian_chedao = "1";//外检车道，检测线代号
    private int TypeModel_tid = 0;//TypeModel的主键tid
    private List<PhotoTypeModel> photoTypeModelList;//照片类型列表

    private int CHECK_MODE = 0;//检测模式 0:外检  1：路试 2：底盘动态
    private String Line = "01";//外检车道
    private String Item_Code = "";//F1外检,R1路试，DC底盘动态
    //    private WaiJainDataModel waiJainDataModel = new WaiJainDataModel();//外检上传数据model
    private String Login_name = "";//当前登录的检测员的名字
    //    private VideoModel model = new VideoModel();
    private List<Boolean> IsTakePhoto = new ArrayList<>();//当前车辆要检测的项目是否拍照的列表
    public static int CruuentStatement = 0;
    TakePhoto takePhoto;
    Uri imageUri;
    int recLen = 0;
    //    Handler handler = new Handler();
//    Runnable runnable = new Runnable() {
//        @Override
//        public void run() {
//            recLen++;
//            if (recLen < 1200) {
//                acWaijianTvJishiqi.setText("项目进行时间：" + recLen + "  秒");
//            }
//            handler.postDelayed(this, 1000);
//        }
//    };
    CountupView mCvCountupViewTest1;
    int Is_An_Huan = 0;
    private An_Huan_Model an_huan_model;
    private HuanBaoModel huanBaoModel;
    private CarsInforModel carsInforModel;
    //    int gotoTakePhotoCounts = 0;//外检上传自己后台次数
//    int gotoTakePhotoCounts2 = 0;//外检上传自己后台次数
//    int gotoTakePhotoCounts3 = 0;//平台次数
    private String my_item_start_time = "", my_item_end_time = "";
    private boolean is_db_data = false;//数据库是否保存数据   false:无   true：有
    List<WaiJianItemModel> books = new ArrayList<>();
    static final String STATE_PHOTO_TYPE = "PHOTO_TYPE";
    static final String STATE_PHOTO_TYPE_huan = "PHOTO_TYPE_huan";
    static final String STATE_typeModel = "typeModel";
    static final String STATE_TypeModel_Position = "TypeModel_Position";
    static final String STATE_wai_jian_photo = "wai_jian_photo";
    static final String STATE_tid = "TypeModel_tid";
    boolean wai_jian_photo = false;
    boolean wai_jian_photo22 = false;
    /**
     * 只有点击环保拍照按钮才会传递此参数，
     * 其他的没有传，用来确保当安检环保都有的情况下能够以此判断，
     * 直接跳转到环保拍照
     */
    int only_huanbao = 0;

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // 保存用户自定义的状态
        savedInstanceState.putString(STATE_PHOTO_TYPE, PHOTO_TYPE);
        savedInstanceState.putString(STATE_PHOTO_TYPE_huan, PHOTO_TYPE_huan);
        savedInstanceState.putSerializable(STATE_typeModel, typeModel);
        savedInstanceState.putInt(STATE_TypeModel_Position, TypeModel_Position);
        savedInstanceState.putInt(STATE_tid, TypeModel_tid);
        savedInstanceState.putBoolean(STATE_wai_jian_photo, wai_jian_photo);
        // 调用父类交给系统处理，这样系统能保存视图层次结构状态
        super.onSaveInstanceState(savedInstanceState);
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // 总是调用超类，以便它可以恢复视图层次超级
        super.onRestoreInstanceState(savedInstanceState);
        // 从已保存的实例中恢复状态成员
        PHOTO_TYPE = savedInstanceState.getString(STATE_PHOTO_TYPE);
        PHOTO_TYPE_huan = savedInstanceState.getString(STATE_PHOTO_TYPE_huan);
        typeModel = (TypeModel) savedInstanceState.getSerializable(STATE_typeModel);
        TypeModel_Position = savedInstanceState.getInt(STATE_TypeModel_Position);
        TypeModel_tid = savedInstanceState.getInt(STATE_tid);
        wai_jian_photo = savedInstanceState.getBoolean(STATE_wai_jian_photo);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_wai_jian_photo);
        ButterKnife.bind(this);
        if (savedInstanceState != null) {
            Log.e("tag", "onCreate---PHOTO_TYPE==" + savedInstanceState.getString(STATE_PHOTO_TYPE));
            Log.e("tag", "onCreate---PHOTO_TYPE_huan==" + savedInstanceState.getString(STATE_PHOTO_TYPE_huan));
            Log.e("tag", "onCreate---TypeModel_tid==" + savedInstanceState.getInt(STATE_tid));
            Log.e("tag", "onCreate---wai_jian_photo==" + savedInstanceState.getBoolean(STATE_wai_jian_photo));
            wai_jian_photo22 = savedInstanceState.getBoolean(STATE_wai_jian_photo);
        } else {
            Log.e("tag", "onCreate---savedInstanceState==null");
        }

        An_Huan_HomeActivity.Is_Check_An = true;
        An_Huan_HomeActivity.Is_Check_Huan = true;
        mCvCountupViewTest1 = (CountupView) findViewById(R.id.ac_waijian_tv_jishiqi_cv_CountupViewTest3);
        mCvCountupViewTest1.setTag("test1");
        long time1 = (long) 1000;
        mCvCountupViewTest1.start(time1);
        String logStrf = "\n" + "onCreate-----外检拍照---WaiJianPhotoActivity-----" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        init();
        CruuentStatement = 0;
//        BaseApplication.BaseApplication_buHeGeModel3List = new ArrayList<>();
        WAIJIAN_PHOTO_PREVIEW_LISTS = new HashMap<>();
        HUANBAO_PHOTO_PREVIEW_LISTS = new HashMap<>();
        instances = this;
        waijian_chedao = getIntent().getExtras().getString("CarDetailsActivity_acCarDetailsWaijianchedao", "");
        UtilsLog.e("waijian_chedao===" + waijian_chedao);
        an_huan_model = (An_Huan_Model) getIntent().getSerializableExtra
                ("CarDetailsActivity_CarsInforModel");
        UtilsLog.e("an_huan_model=55=" + an_huan_model.toString());
//        carsInforModel = getIntent().getExtras().getParcelable("CarDetailsActivity_CarsInforModel");
        Login_name = getIntent().getExtras().getString("login_w_name", "");
        UtilsLog.e("Login_name=Login_name=" + Login_name);
        Is_An_Huan = getIntent().getExtras().getInt("Is_An_Huan", 0);
        UtilsLog.e("Is_An_Huan===" + Is_An_Huan);

        only_huanbao = getIntent().getExtras().getInt("only_huanbao", 0);
        UtilsLog.e("only_huanbao===" + only_huanbao);
        // 0:安检  1：环保  2:两者都有
        switch (Is_An_Huan) {
            case 0:
                carsInforModel = an_huan_model.getCarsInforModel();
                if (wai_jian_photo22 == false) {
                    UtilsLog.e("tag", "tid====11111111111111111111111");
                    getOutPhotoItem(1);
                } else {
                    UtilsLog.e("tag", "tid====222222222222222");
                    CruuentStatement = 0;
                    changePhotoList();
                }
//                getOutPhotoItem(1);
                acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
                acWaijianBtnHuanPhotoTake.setEnabled(false);
                break;
            case 1:
                acWaijianBtnAnPhotoTake.setEnabled(false);
                CruuentStatement = 1;
                huanBaoModel = an_huan_model.getHuanBaoModel();
                acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
                acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                TypeModel typeModel22 = null;
                typeModelListAdapter = new ArrayList<>();
                for (int i = 0; i < Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS.length; i++) {
                    String name = Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][0];
                    typeModel22 = new TypeModel();
                    typeModel22.setName(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][0]);
//                    typeModel22.setCode(Constants.HUANBAO_PHOTO_LISTS[i][1]);
                    typeModel22.setCodehuan(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][1]);
                    typeModel22.setNumber(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][2]);
                    typeModel22.setIsanhuan(1);//环保
                    typeModel22.setIsphoto(0);//未拍照
                    typeModel22.setTid(i + 1);
                    typeModelListAdapter.add(typeModel22);
                }
                TypeModel typeModelDAO = null;
                for (int i = 0; i < typeModelListAdapter.size(); i++) {
                    UtilsLog.e("typeModelListAdapter===" + typeModelListAdapter.get(i).toString());
                    typeModelDAO = new TypeModel();
                    typeModelDAO = typeModelListAdapter.get(i);
                    typeModelDAO.save();
                }
                changePhotoList();
                break;
            case 2:
                carsInforModel = an_huan_model.getCarsInforModel();
                huanBaoModel = an_huan_model.getHuanBaoModel();
                if (wai_jian_photo22 == false) {
                    UtilsLog.e("tag", "tid====3333333333333333333");
                    getOutPhotoItem(1);

                } else {
                    UtilsLog.e("tag", "tid====4444444444444444");
                    CruuentStatement = 0;
                    changePhotoList();

//                    acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
//                    acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                }
                acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);

                break;
        }
        //获取去图片类型列表
//        getDataPhotoTypeList();

        CHECK_MODE = BaseApplication.JIANCE_MODE;
        UtilsLog.e("WaiJianPhotoActivity---CHECK_MODE==" + CHECK_MODE);
        Line = getIntent().getStringExtra("CarDetailsActivity_Line");
        switch (CHECK_MODE) {
            case 0:
                Item_Code = "F1";
                break;
            case 1:
                Item_Code = "R1";
                break;
            case 2:
                Item_Code = "DC";
                break;
        }
        books = WaiJianItemModel.listAll(WaiJianItemModel.class);
        if (books != null && books.size() > 0) {
            is_db_data = true;
            UtilsLog.e("WaiJianPhotoActivity----本地数据库查询----不为空==" + books.toString());
            for (int i = 0; i < books.size(); i++) {
//                WaiJianItemModel.delete(books.get(i));
            }
        } else {
            is_db_data = false;
            UtilsLog.e("WaiJianPhotoActivity----本地数据库查询----空==");
        }

//        List<TypeModel> list2222 = new ArrayList<>();
//        if (CruuentStatement == 0) {
//            list2222 = TypeModel.find(TypeModel.class,
//                    "isanhuan=? or isanhuan=? ", "0", "2");
//        } else {
//            list2222 = TypeModel.find(TypeModel.class,
//                    "isanhuan=? or isanhuan=? ", "1", "2");
//        }
//        if (list2222 != null && list2222.size() > 0) {
//            for (int i = 0; i < list2222.size(); i++) {
//                UtilsLog.e("list2222====" + list2222.get(i).toString());
//            }
//        }
//
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("tag", "onResume---PHOTO_TYPE==" + PHOTO_TYPE);
        Log.e("tag", "onResume---PHOTO_TYPE_huan==" + PHOTO_TYPE_huan);
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Log.e("tag", "拍照失败==" + msg);
        String logStr = "\n" + "外检项目拍照----拍照失败==" + "\n" + msg;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        ArrayList<TImage> images = result.getImages();
        if (images != null && images.size() > 0) {
            String photo_file_path = images.get(0).getCompressPath();
            String photo_file_path2 = images.get(0).getOriginalPath();
            Log.e("tag", "拍照失败--path==" + photo_file_path);
            Log.e("tag", "拍照失败--path=22=" + photo_file_path2);
        }
    }

    String photo_file_path_OriginalPath;
    int FLAG = 1;//0:拍照   1：相册

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        Log.e("tag", "takeSuccess---PHOTO_TYPE==" + PHOTO_TYPE);
        Log.e("tag", "takeSuccess---PHOTO_TYPE_huan==" + PHOTO_TYPE_huan);
        Log.e("tag", "111111111111");
        String logStr = "\n" + "---外检上传照片--- takeSuccess==" +
                "\n" + "PHOTO_TYPE::" + PHOTO_TYPE + "\n"
                + "PHOTO_TYPE_huan::" + PHOTO_TYPE_huan + "\n" +
                "img_number:" + img_number + "\n" +
                "img_code:" + img_code + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        if (result != null) {
//            showImg(result.getImages());
            ArrayList<TImage> images = result.getImages();
            if (images != null && images.size() > 0) {
                //压缩后的图片路径，不压缩为null
//                photo_file_path = images.get(0).getCompressPath();
                Log.e("tag", "拍照成功--path=111=" + images.get(0).getOriginalPath());
                Log.e("tag", "拍照成功--path=Environment=" + Environment.getExternalStorageDirectory());
                ///storage/emulated/0
                if (FLAG == 1) {
                    //拍照
                    if (SystemUtil.getSystemModel().contains("GIONEE") || SystemUtil.getSystemModel().contains("gionee")) {
                        //金立手机的路线
                        photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                                .getOriginalPath().replace("my_images/", "");
                        Log.e("tag", "拍照成功-金立手机-path=22=" + photo_file_path_OriginalPath);
                    } else {
                        //其他手机
                        /***
                         * @question 拍照返回的照片的路径处理
                         * @method 有的手机返回的照片带有/storage/emulated/0，
                         * @method 有的不带，所以需要分别处理
                         * @import 找个地方划重点，考试要考的，TDM CD
                         */
                        if (images.get(0).getOriginalPath().contains("storage/emulated")) {
                            photo_file_path_OriginalPath = images.get(0).getOriginalPath().replace("my_images/", "");
                        } else {
                            photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
                                    .getOriginalPath().replace("my_images/", "");
                        }
//                    photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                            .getOriginalPath().replace("my_images/", "");
                        Log.e("tag", "拍照成功--path=22=" + photo_file_path_OriginalPath);
                    }
//                    try {
//                        FileInputStream in = new FileInputStream(photo_file_path_OriginalPath);
//                        Bitmap bitmap = BitmapFactory.decodeStream(in);
//                        MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "", "");
//                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//                        Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));
//                        intent.setData(uri);
//                        instances.sendBroadcast(intent);
//                    } catch (FileNotFoundException e) {
//                        String ee = e.getMessage() + "===" + e.getLocalizedMessage() + "===" + e.getCause() + "===" + e.toString();
//                        Log.e("tag", "拍照成功--通知相册刷新失败=" + ee);
//                        e.printStackTrace();
//                    }
                } else {
                    //相册
                    photo_file_path_OriginalPath = images.get(0)
                            .getOriginalPath().replace("my_images/", "");
                    Log.e("tag", "相册--path=2234343434=" + photo_file_path_OriginalPath);
                }
//                //原图片的路径
//                photo_file_path_OriginalPath = Environment.getExternalStorageDirectory() + images.get(0)
//                        .getOriginalPath().replace("my_images/", "");
//                Log.e("tag", "拍照成功--path=22=" + photo_file_path_OriginalPath);
                if (!TextUtils.isEmpty(photo_file_path_OriginalPath)) {
//                    Log.e("tag", "拍照成功--path=33=" + img_imageUri_path);
//                    if (SharedPreferencesUtils.getPhotoClipping(instances)) {
//                        //拍照需要编辑的
//                        Intent intent = new Intent(instances, WaiRotatePhotoActivity.class);
//                        intent.putExtra("wa_rotate_img", photo_file_path_OriginalPath);
//                        startActivityForResult(intent, 917);
//                    } else {
                    //拍照不需要编辑的
                    Luban.with(instances)
                            .load(new File(photo_file_path_OriginalPath))                     //传人要压缩的图片
                            .setCompressListener(new OnCompressListener() { //设置回调
                                @Override
                                public void onStart() {
                                    // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                }

                                @Override
                                public void onSuccess(File file) {
                                    // TODO 压缩成功后调用，返回压缩后的图片文件
                                    Log.e("tag", "压缩成功后调用");
                                    //拍照压缩后上传
//                                    getData(file,picFileFullName);
                                    switch (Is_An_Huan) {
                                        case 0:
                                            Log.e("tag", "Luban---PHOTO_TYPE==" + PHOTO_TYPE);
                                            Log.e("tag", "Luban---PHOTO_TYPE_huan==" + PHOTO_TYPE_huan);
                                            getData(file, photo_file_path_OriginalPath);
                                            break;
                                        case 1:
                                            if (!TextUtils.isEmpty(PHOTO_TYPE_huan) && !PHOTO_TYPE_huan.equals("null")) {
                                                if (PHOTO_TYPE_huan.contains("100")) {
                                                    getDataUploadPhoto_HuanBao(file, photo_file_path_OriginalPath, true);
                                                }
                                            }
                                            break;
                                        case 2:
                                            if (PHOTO_TYPE != null)
                                                getData(file, photo_file_path_OriginalPath);
                                            if (!TextUtils.isEmpty(PHOTO_TYPE_huan) && !PHOTO_TYPE_huan.equals("null")) {
                                                if (PHOTO_TYPE_huan.contains("100")) {
                                                    getDataUploadPhoto_HuanBao(file, photo_file_path_OriginalPath, true);
                                                }
                                            }

                                            break;
                                    }
                                }

                                @Override
                                public void onError(Throwable e) {
                                    // TODO 当压缩过程出现问题时调用
                                    Toast.makeText(instances, "图片压缩出现问题，请重试", Toast.LENGTH_LONG).show();
                                }
                            }).launch();    //启动压缩
                }
//                }
            }
        }
    }

    @OnClick({
            R.id.ac_waijian_btn_buhege2, R.id.ac_waijian_btn_wancheng2,
            R.id.ac_waijian_btn_other_imags, R.id.ac_waijian_btn_an_photo_take
            , R.id.ac_waijian_btn_huan_photo_take, R.id.ac_waijian_right_txt
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ac_waijian_right_txt:
                //其他外检照片
                String logStr3 = "\n" + "外检-其他拍照照片按钮点击" + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
                Intent intent_3 = new Intent(WaiJianPhotoActivity.this, OtherWaiJianPhotoActivity.class);
                startActivityForResult(intent_3, 404);
                break;
            case R.id.ac_waijian_btn_an_photo_take:
                //安检拍照列表切换
                CruuentStatement = 0;
//                contentAdapter2.notifyDataSetInvalidated();
                changePhotoList();
                acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
//                this.getResources().get

//                acWaijianBtnAnPhotoTake.setTextColor(this.getResources().getColor(R.color.red));
//                acWaijianBtnHuanPhotoTake.setTextColor(this.getResources().getColor(R.color.white));
                break;
            case R.id.ac_waijian_btn_huan_photo_take:
                //环保拍照列表切换
                CruuentStatement = 1;
                changePhotoList();
//                contentAdapter2.notifyDataSetInvalidated();
                acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
                acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
//                acWaijianBtnAnPhotoTake.setTextColor(this.getResources().getColor(R.color.white));
//                acWaijianBtnHuanPhotoTake.setTextColor(this.getResources().getColor(R.color.red));
                break;
            case R.id.ac_waijian_btn_wancheng2:
                //外检完成
                String logStr = "\n" + "点击外检完成按钮---";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());

//                waiJainDataModel.setDetection_ID(String.valueOf(carsInforModel.getID()));
//                waiJainDataModel.setGUID(carsInforModel.getGUID());
//                waiJainDataModel.setDetectionDevID(CommonUtils.getIMEI(this));
//                waiJainDataModel.setBrakeForce(carsInforModel.getBrakeForce());
////                waiJainDataModel.setPlateNO(carsInforModel.getPlateNO());
//                waiJainDataModel.setPlateNO(carsInforModel.getPlateRegion() + carsInforModel.getPlateNO());
//                waiJainDataModel.setAirAdmission(carsInforModel.getAirAdmission());
//
//                try {
////                    String name = URLDecoder.decode(BaseApplication.accountModelList.get(0).getUserName(),
////                            "UTF-8");
//                    String name = URLDecoder.decode(Login_name, "UTF-8");
//                    waiJainDataModel.setAppearanceInspector(name);//检测员名字，汉字
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
//
//                waiJainDataModel.setAppearanceNo(BaseApplication.accountModelList.get(0).getIDNumber());
//
//                waiJainDataModel.setApprovedLoad(carsInforModel.getApprovedLoad());
//                waiJainDataModel.setArea(carsInforModel.getArea());
//                waiJainDataModel.setBodyColor(carsInforModel.getBodyColor());
//                waiJainDataModel.setBrand(carsInforModel.getBrand());
//                waiJainDataModel.setCarBodyType(carsInforModel.getCarBodyType());
//                waiJainDataModel.setCarID(carsInforModel.getCarID());
//                waiJainDataModel.setCarModel(carsInforModel.getCarModel());
//                waiJainDataModel.setCarTypeLevel(carsInforModel.getCarTypeLevel());
//                waiJainDataModel.setCategory(carsInforModel.getCategory());
//                waiJainDataModel.setCentralAxle(carsInforModel.getCentralAxle());
//                waiJainDataModel.setCode(carsInforModel.getCode());
//                waiJainDataModel.setCombCarNO(carsInforModel.getCombCarNO());
//                waiJainDataModel.setCurbWeight(carsInforModel.getCurbWeight());
//                waiJainDataModel.setDetectDate(carsInforModel.getDetectDate());
//                waiJainDataModel.setDetectionCategory(carsInforModel.getDetectionCategory());
//                waiJainDataModel.setDetectionStatus(carsInforModel.getDetectionStatus());
//                waiJainDataModel.setDisplacement(carsInforModel.getDisplacement());
//                waiJainDataModel.setDriveAxle(carsInforModel.getDriveAxle());
//                waiJainDataModel.setDriverAxleWeight(carsInforModel.getDriverAxleWeight());
//                waiJainDataModel.setDriverTypeName(carsInforModel.getDriverTypeName());
//                waiJainDataModel.setDriverType(carsInforModel.getDriverType());
//                waiJainDataModel.setPlateType(carsInforModel.getPlateType());
//                waiJainDataModel.setItemcode(Item_Code);
//                waiJainDataModel.setLine(Line);
//                waiJainDataModel.setMainAxis(carsInforModel.getMainAxis());
//                waiJainDataModel.setParkingAxle(carsInforModel.getParkingAxle());
//                waiJainDataModel.setEngineNO(carsInforModel.getEngineNO());
//                waiJainDataModel.setFuelType(carsInforModel.getFuelType());
//                waiJainDataModel.setPlateTypeName(carsInforModel.getPlateTypeName());
//                waiJainDataModel.setPlatformSN(carsInforModel.getPlatformSN());
//                waiJainDataModel.setQueueID(carsInforModel.getQueueID());
//                waiJainDataModel.setSN(carsInforModel.getSN());
//                waiJainDataModel.setStatus(carsInforModel.getStatus());
//                waiJainDataModel.setTest_times(carsInforModel.getTimes());
//                waiJainDataModel.setType(carsInforModel.getType());
//                waiJainDataModel.setVIN(carsInforModel.getVIN());
//                appendCode2AndValues();
//
//                model.setItemcode(Item_Code);
//                model.setLine(Line);
//                model.setPlateNO(carsInforModel.getPlateRegion() + carsInforModel.getPlateNO());
//                model.setPlateType(carsInforModel.getPlateType());
//                model.setPlatformSN(carsInforModel.getPlatformSN());
//                model.setTest_times(carsInforModel.getTimes());


//                if (CommonUtils.isOnline(instances)) {
//                    //上传平台的数据
////                    waiJainDataModel.setDataType("F1");
////                    uploadPlatformData_w(waiJainDataModel);
////                        getDataReportData();
//                    //视频接口上传数据
//                    model.setDetectionItemStartDate(BaseApplication.W_ItemStart_time);
//                    model.setDetectionItemEndDate(BaseApplication.W_ItemEnd_time);
//                    model.setDetectionID(String.valueOf(carsInforModel.getID()));
//                    uploadVideo(model);
//                    String logStr33 = "\n" + "点击外检完成按钮--333-";
//                    PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr33.getBytes());
//                    //让按钮变成不可点击
////                        acWaijianBtnWancheng2.setEnabled(false);
////                    getDataReportData();
//                } else {
//                    Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
//                            .LENGTH_LONG).show();
//                }

                finish();
                break;
            case R.id.ac_waijian_btn_buhege2:
//                String logStr2 = "\n" + "外检不合格项目按钮点击" + "\n";
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
//                //不合格项目录入
////                Intent intent = new Intent(WaiJianPhotoActivity.this, DisqualificationActivity.class);
////                intent.putExtra("buhege_flag", 0);//不合格项目跳转 0：外检 1：底盘动态
////                intent.putExtra("WaiJianPhotoActivity_CarsInforModel", carsInforModel);
////                startActivity(intent);
//                Intent intent_2 = new Intent(WaiJianPhotoActivity.this, WaiJianResultActivity.class);
//                intent_2.putExtra("WaiJianPhotoActivity_CarsInforModel", carsInforModel);
//                startActivity(intent_2);
                break;
            case R.id.ac_waijian_btn_other_imags:
//                String logStr3 = "\n" + "外检-其他拍照照片按钮点击" + "\n";
//                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
//                Intent intent_3 = new Intent(WaiJianPhotoActivity.this, OtherWaiJianPhotoActivity.class);
//                startActivityForResult(intent_3, 404);
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            List<OtherWaiJianPhotoModel> list = (List<OtherWaiJianPhotoModel>) data.getSerializableExtra("othet_waijian_photo");
            switch (requestCode) {
                case 404:
                    if (list != null && list.size() > 0) {

//                        //去掉可能重复的
//                        for (int i = 0; i < typeModelListAdapter.size(); i++) {
//                            for (int j = 0; j < list.size(); j++) {
//                                if ((list.get(j).getName()).equals(typeModelListAdapter.get(i).getName())) {
//                                    typeModelListAdapter.remove(i);
//                                }
//                            }
//                        }
//
//                        //添加新选择的外检拍照
//                        TypeModel typeModel = null;
//                        for (int j = 0; j < list.size(); j++) {
//                            typeModel = new TypeModel();
//                            typeModel.setName(list.get(j).getName());
//                            typeModel.setCode(list.get(j).getCode());
//                            typeModelListAdapter.add(typeModel);
//                        }

//                        //重新适配listview
//                        contentAdapter2 = new ContentAdapter2(instances, typeModelListAdapter,
//                                mListener, instances);
//                        acWaijianPhotoListview.setAdapter(contentAdapter2);
//                        setListViewHeightBasedONChildren(acWaijianPhotoListview);


                        for (int i = 0; i < list.size(); i++) {
                            if (!TextUtils.isEmpty(list.get(i).getName()) && list.get(i).getName() != "") {
                                //查询是否已存在对应的Name
                                List<TypeModel> modelList = TypeModel.find(TypeModel.class,
                                        "Name=?", list.get(i).getName());
                                List<TypeModel> listAll = TypeModel.listAll(TypeModel.class);
                                if (modelList != null && modelList.size() > 0) {
                                    //如果查询出结果表示数据库中已存在，跳出当前循环，继续下一个循环
                                    continue;
                                } else {
                                    if (listAll != null && listAll.size() > 0) {
                                        typeModel = new TypeModel();
                                        typeModel.setName(list.get(i).getName());
                                        typeModel.setCode(list.get(i).getCode());
                                        typeModel.setCodean(list.get(i).getCode());
                                        typeModel.setIsanhuan(0);//安检
                                        typeModel.setIsphoto(0);//未拍照
                                        typeModel.setTid(listAll.size() - 1 + i + 1);
                                        typeModel.save();
                                    } else {
                                        UtilsLog.e("点击选择其他外检照片--返回时查询已经保存数据库的照片列表为空");
                                    }
                                }
                            }
                        }
                        changePhotoList();
                    }
                    break;
            }
        }
    }


    private void getData(File file, String file_name) {
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getIP(instances))) {
            if (CommonUtils.isOnline(instances)) {
                getDataUploadPhoto(file, file_name);
            } else {
                Toast.makeText(instances, getResources().getString(R.string.network_error), Toast
                        .LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(this, "请设置IP与端口号", Toast.LENGTH_LONG).show();
        }
    }

    //上传照片
    private void getDataUploadPhoto(final File file, final String file_name) {
        Log.e("tag", "getDataUploadPhoto---TypeModel_Position==" + TypeModel_Position);
        Log.e("tag", "getDataUploadPhoto---PHOTO_TYPE==" + PHOTO_TYPE);
        Log.e("tag", "getDataUploadPhoto---PHOTO_TYPE_huan==" + PHOTO_TYPE_huan);
        Log.e("tag", "getDataUploadPhoto---TypeModel_tid==" + TypeModel_tid);
        Log.e("tag", "getDataUploadPhoto---wai_jian_photo==" + wai_jian_photo);
        UtilsLog.e("getDataUploadPhoto---url==" + SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO);
        String car_no = "";
//        if (SharedPreferencesUtils.getAddress(instances).equals("温州")) {
//            car_no = carsInforModel.getPlateRegion()
//                    + carsInforModel.getPlateNO()
//                    + carsInforModel.getPlateExtra();
//        } else if (SharedPreferencesUtils.getAddress(instances).equals("常山")) {
        car_no = carsInforModel.getPlateRegion()
                + carsInforModel.getPlateNO();
//        }
        String str = "QueueID:" + carsInforModel.getQueueID() + "\n" +
                "GUID:" + carsInforModel.getGUID() + "\n" +
                "Times:" + carsInforModel.getTimes() + "\n" +
                "PlatformSN:" + carsInforModel.getPlatformSN() + "\n" +
                "SN:" + carsInforModel.getSN() + "\n" +
                "PhotoDate:" + DateUtil.currentTime2() + "\n" +
                "PhotoType:" + PHOTO_TYPE + "\n" +
                "Type:" + carsInforModel.getType() + "\n" +
                "CarNO:" + car_no + "\n" +
                "PlateType:" + carsInforModel.getPlateType() + "\n" +
                "ItemCode:" + "F1" + "\n" +
                "Line:" + waijian_chedao + "\n" +
                "VIN:" + carsInforModel.getVIN() + "\n" +
                "AppearanceInspector:" + Login_name + "\n" +
                "NAME_LOG" + NAME_LOG + "\n" +
                "FileType:" + "jpg" + "\n";
        UtilsLog.e("安检getDataUploadPhoto---json==" + str);

        String logStr = "\n" + "安检---外检上传照片---json==" +
                "\n" + "json::" + str + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getFileIP(instances) + UPLOAD_PHOTO).tag(instances)
                .params("AppearanceInspector", Login_name)
                //guid
                .params("QueueID", carsInforModel.getQueueID())
                //guid
                .params("GUID", carsInforModel.getGUID())
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                //SN
                .params("SN", carsInforModel.getSN())
                //拍摄时间
                .params("PhotoDate", DateUtil.currentTime2())
                //照片类型-拍的哪里的照片，位置
//                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
                .params("PhotoType", PHOTO_TYPE)
                //车辆类型
                .params("Type", carsInforModel.getType())
                //车牌号码，两个拼起来的
                .params("CarNO", car_no)
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //拍照code F1表示外检
                .params("ItemCode", "F1")
                //外检车道，检测线代号
                .params("Line", waijian_chedao)
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                .params("FileType", "jpg")
//                .params("FileType", FileUtils.getExtensionName(file.getName()))
                //照片
                .params("zp", file)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");

                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("getDataUploadPhoto-result==" + result);

                        String logStr = "\n" + "外检上传照片--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_PHOTO + "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        UtilsLog.e("response.headers()-result==" + response.headers());
//                        photo_result(PHOTO_TYPE);
//                        if (PHOTO_TYPE != null) {
//                            WAIJIAN_PHOTO_PREVIEW_LISTS.put(Integer.parseInt(PHOTO_TYPE), file);
//                        }
                        WAIJIAN_PHOTO_PREVIEW_LISTS.put(PHOTO_TYPE, file);
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("getDataUploadPhoto-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                try {
                                    if (!TextUtils.isEmpty(file_name)) {
                                        CommonUtils.DeleteImage(instances, file_name);
                                        String[] str_photo_path = file_name.split("Pictures");

                                        UtilsLog.e("str_photo_path[0]===" + str_photo_path[0]);
                                        UtilsLog.e("str_photo_path[1]===" + str_photo_path[1]);
                                        FileUtils.deleteDirectory(Environment
                                                .getExternalStorageDirectory() + "/Pictures" +
                                                str_photo_path[1]);
                                    } else {
                                        String logStr2 = "\n" + "外检上传照片--没有获取到即将删除的图片路径" + "\n";
                                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE,
                                                logStr2.getBytes());
                                        UtilsLog.e("getDataUploadPhoto==没有获取到即将删除的图片路径");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                UtilsLog.e("tag", "onSuccess---tid==" + typeModel.getTid());
                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
//                                typeModel.setColor(1);
//                                typeModel.setIsphoto(1);
////                                typeModel.update();
//                                typeModel.save();
//                                list.set(TypeModel_Position, typeModel);
//                                contentAdapter2.notifyDataSetChanged();

//                                Goods good2 = Goods.findById(Goods.class, 1);
//                                good2.setName("Rice");
//                                good2.save();
                                if (TypeModel_tid != 0) {
                                    List<TypeModel> modelList = TypeModel.find(TypeModel.class, "tid=?", String.valueOf(TypeModel_tid));
                                    if (modelList != null && modelList.size() > 0) {
                                        TypeModel model2 = modelList.get(0);
                                        model2.setColor(1);
                                        model2.setIsphoto(1);
                                        model2.update();
//                                    model2.save();
                                        changePhotoList();
                                    } else {
                                        UtilsLog.e("tag", "onSuccess---model2==null");
                                    }
                                }
                            }
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        UtilsLog.e("getDataUploadPhoto-onError==" + response.body());
                        UtilsLog.e("getDataUploadPhoto-onError==" + response.getException());
                        String logStr = "\n" + "外检上传照片-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getFileIP(instances) +
                                UPLOAD_PHOTO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                        Toast.makeText(instances, "上传照片失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
        mCvCountupViewTest1.stop();
//        List<TypeModel> books = TypeModel.listAll(TypeModel.class);
//        if (books != null && books.size() > 0) {
//            for (int i = 0; i < books.size(); i++) {
//                TypeModel.delete(books.get(i));
//            }
//        }
    }


    //切换--安检--环保--拍照列表
    //0：安检  1：环保
    List<TypeModel> list = new ArrayList<>();

    void changePhotoList() {
        if (CruuentStatement == 0) {
            list = TypeModel.find(TypeModel.class,
                    "isanhuan=? or isanhuan=? ", "0", "2");
        } else {
            list = TypeModel.find(TypeModel.class,
                    "isanhuan=? or isanhuan=? ", "1", "2");
        }
//        for (int i = 0; i < list.size(); i++) {
//            UtilsLog.e("list===55===" + list.get(i).toString());
//        }
        if (list != null && list.size() > 0) {
//            list.removeIf(a->a.getCodean()!=null||a.getCodean()!=""||a.getCodean()!="null");
            contentAdapter2 = new ContentAdapter2(instances, list,
                    mListener, instances);
            acWaijianPhotoListview.setAdapter(contentAdapter2);
            setListViewHeightBasedONChildren(acWaijianPhotoListview);
            acWaijianPhotoListview.setOnItemClickListener(instances);
        }
    }

    //获取某辆车的外检拍照的项目
    // PlateType,CarType,Usage
    String json_str_getOutPhotoItem;

    //0:安检  1：安检环保都有
    private void getOutPhotoItem(int mode) {
        OutPhotoItem model = new OutPhotoItem();
        model.setCarType(carsInforModel.getType());
        model.setPlateType(carsInforModel.getPlateType());
        model.setUsage(carsInforModel.getUsage());
        model.setPlatformSN(carsInforModel.getPlatformSN());
        Gson gson = new Gson();
        json_str_getOutPhotoItem = gson.toJson(model);
        UtilsLog.e("getOutPhotoItem---json_str==" + json_str_getOutPhotoItem);
        UtilsLog.e("getOutPhotoItem---url==" + SharedPreferencesUtils.getIP(this) + WAI_JIAN_PHOTO_ITEM);
        OkGo.<String>post(SharedPreferencesUtils.getIP(this) + WAI_JIAN_PHOTO_ITEM).tag(this)
                .upJson(json_str_getOutPhotoItem)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        BaseApplication.msg = result;
//                        UtilsLog.e("getOutPhotoItem-result==" + result);
                        CommonUtils.hideLoadingDialog(instances);
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("getOutPhotoItem-newResult==" + newResult);

                        String logStr = "\n" + "外检--获取某辆车的外检拍照的项目--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getIP(instances) +
                                WAI_JIAN_PHOTO_ITEM + "\n" + "JSON::" + json_str_getOutPhotoItem
                                + "\n" + "result::" + newResult;
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());

                        if (!TextUtils.isEmpty(newResult) && !"[[]]".equals(newResult) && !"[{}]".equals
                                (newResult) && !"[]".equals(result)) {
                            typeModelList_an = JsonUtil.stringToArray(newResult,
                                    TypeModel[].class);
                            if (typeModelList_an != null && typeModelList_an.size() > 0) {
                                String logStr22 = "\n" + "外检--获取某辆车的外检拍照的项目--请求成功" +
                                        "\n" + "typeModelList_an::" + typeModelList_an.toString()
                                        + "\n";
                                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());


//                                TypeModel hh_typeModel = null;
//                                for (int i = 0; i < Constants.HH_PHOTO.length; i++) {
//                                    hh_typeModel = new TypeModel();
//                                    hh_typeModel.setCode(Constants.HH_PHOTO[i][1]);
//                                    hh_typeModel.setName(Constants.HH_PHOTO[i][0]);
//                                    typeModelList_an.add(hh_typeModel);
//                                }

//                                typeModelList_an.removeIf(a->a.getCode()!=null||a.getCode()!=""||a.getCode()!="null");
                                TypeModel typeModel = null;
                                if (mode == 0) {
                                    for (int i = 0; i < typeModelList_an.size(); i++) {
                                        typeModel = new TypeModel();
                                        typeModel.setName(typeModelList_an.get(i).getName());
                                        typeModel.setCodean(typeModelList_an.get(i).getCode());
                                        typeModel.setIsanhuan(0);//安检
                                        typeModel.setIsphoto(0);//未拍照
                                        typeModel.setTid(i + 1);
                                        typeModelListAdapter.add(typeModel);
                                    }
                                } else {
                                    wai_jian_photo = true;
                                    for (int i = 0; i < typeModelList_an.size(); i++) {
                                        typeModel = new TypeModel();
                                        String name = "";
                                        if (!TextUtils.isEmpty(typeModelList_an.get(i).getName())) {
                                            name = typeModelList_an.get(i).getName();
                                        } else {
                                            name = typeModelList_an.get(i).getCode();
                                        }
                                        typeModel.setCodean(typeModelList_an.get(i).getCode());
                                        if (name.contains("左前方")) {
                                            typeModel.setIsanhuan(2);
                                            typeModel.setCodehuan("1002");
                                            typeModel.setNumber("01");
                                        } else if (name.contains("右后方")) {
                                            typeModel.setIsanhuan(2);
                                            typeModel.setCodehuan("1002");
                                            typeModel.setNumber("02");
                                        } else if (name.contains("车辆识别")) {
                                            typeModel.setIsanhuan(2);
                                            typeModel.setCodehuan("1002");
                                            typeModel.setNumber("03");
                                        } else if (name.contains("发动机号")) {
                                            typeModel.setIsanhuan(2);
                                            typeModel.setCodehuan("1002");
                                            typeModel.setNumber("04");
                                        } else {
                                            typeModel.setIsanhuan(0);
                                        }
                                        typeModel.setName(name);
                                        typeModel.setIsphoto(0);//未拍照
                                        typeModel.setTid(i + 1);
                                        typeModelListAdapter.add(typeModel);
                                    }

                                    for (int i = 0; i < Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS.length; i++) {
                                        String name = Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][0];
                                        typeModel = new TypeModel();
                                        if (name.contains("左前")) {
                                            continue;
                                        } else if (name.contains("右后")) {
                                            continue;
                                        } else if (name.contains("车辆识别")) {
                                            continue;
                                        } else if (name.contains("发动机号")) {
                                            continue;
                                        }
                                        typeModel.setName(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][0]);
                                        typeModel.setCodehuan(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][1]);
                                        typeModel.setNumber(Constants.HU_ZHOU_HUANBAO_PHOTO_LISTS[i][2]);
                                        typeModel.setIsanhuan(1);//环保
                                        typeModel.setIsphoto(0);//未拍照
                                        typeModel.setTid(typeModelListAdapter.size() + i + 1);
//                                        typeModelList_huan.add(typeModel);
                                        typeModelListAdapter.add(typeModel);
                                    }
                                }
                                String logStr2 = "\n" + "外检--获取某辆车的外检拍照的项目--合集---" +
                                        "\n" + "typeModelListAdapter::" + typeModelListAdapter.toString();
                             //   PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
                                TypeModel typeModelDAO = null;
                                for (int i = 0; i < typeModelListAdapter.size(); i++) {
//                                    UtilsLog.e("typeModelListAdapter===" + typeModelListAdapter.get(i).toString());
                                    typeModelDAO = new TypeModel();
                                    typeModelDAO = typeModelListAdapter.get(i);
                                    typeModelDAO.save();
                                }

                                if (only_huanbao == 1) {
                                    UtilsLog.e("only_huanbao====00000000000000");
                                    //环保拍照列表切换
                                    CruuentStatement = 1;
                                    changePhotoList();
                                    acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
                                    acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                                } else {
                                    CruuentStatement = 0;
                                    changePhotoList();
                                    acWaijianBtnAnPhotoTake.setBackgroundResource(R.drawable.my_shape_photo);
                                    acWaijianBtnHuanPhotoTake.setBackgroundResource(R.drawable.my_shape_photo_gray);
                                    UtilsLog.e("only_huanbao====11111111111111");
                                }
                            }
                        } else {
                            String logStr2 = "\n" + "外检--获取某辆车的外检拍照的项目--失败" +
                                    "\n" + "result::" + result;
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
                            BaseApplication.msg = result;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        BaseApplication.msg = response.body() + "==" + response.message();
                        UtilsLog.e("getOutPhotoItem-onError==" + response.body());
                        String logStr = "\n" + "外检--获取某辆车的外检拍照的项目-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getIP(instances) +
                                WAI_JIAN_PHOTO_ITEM + "\n" + "result::" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);
                    }
                });
    }


    public static void setListViewHeightBasedONChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    private List<TypeModel> typeModelList_an, typeModelList_huan;
    private List<TypeModel> typeModelListAdapter;
    private ContentAdapter2 contentAdapter2;

    private void init() {
        typeModelList_an = new ArrayList<>();
        typeModelList_huan = new ArrayList<>();
        typeModelListAdapter = new ArrayList<>();
    }

    //响应item点击事件
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
        TypeModel model = (TypeModel) arg0.getAdapter().getItem(position);
        UtilsLog.e("onItemClick==" + model.toString());

    }

    /**
     * 实现类，响应按钮点击事件
     */
    TypeModel typeModel;
    int TypeModel_Position = 0;
    String img_code = "", img_number = "";
    int current_state_an_huan = 0;
    ContentAdapter2.MyClickListener mListener = new ContentAdapter2.MyClickListener() {
        @Override
        public void myOnClick(int position, View v, int flag) {
            PHOTO_TYPE = list.get(position).getCodean();
            NAME_LOG = list.get(position).getName();
            PHOTO_TYPE_huan = list.get(position).getCodehuan();
            TypeModel_tid = list.get(position).getTid();
            Log.e("tag", "takePhoto---PHOTO_TYPE==" + PHOTO_TYPE);
            Log.e("tag", "takePhoto---PHOTO_TYPE_huan==" + PHOTO_TYPE_huan);
            Log.e("tag", "takePhoto---TypeModel_tid==" + TypeModel_tid);
            TypeModel_Position = position;
            FLAG = flag;
            if (flag == 1) {
                Log.e("tag", "takePhoto---takePhoto");
                takePhoto = getTakePhoto();
                TakePhotoOptions takePhotoOptions = new TakePhotoOptions.Builder().setCorrectImage(false).create();
                takePhoto.setTakePhotoOptions(takePhotoOptions);
                File file = new File(Environment.getExternalStorageDirectory(), "/temp_my_app/" + System
                        .currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                imageUri = Uri.fromFile(file);
                takePhoto.onPickFromCapture(imageUri);
                typeModel = new TypeModel();
                typeModel.setName(list.get(position).getName());
                typeModel.setCode(list.get(position).getCode());
                typeModel.setCodean(list.get(position).getCodean());
                typeModel.setNumber(list.get(position).getNumber());
                typeModel.setCodehuan(list.get(position).getCodehuan());
                typeModel.setIsanhuan(list.get(position).getIsanhuan());
                typeModel.setTid(list.get(position).getTid());
                UtilsLog.e("tag", "takePhoto---tid==" + list.get(position).getTid());
                UtilsLog.e("tag", "takePhoto---tid==" + typeModel.getTid());
                img_code = typeModel.getCodehuan();
                img_number = typeModel.getNumber();
                current_state_an_huan = list.get(position).getIsanhuan();
                String logStr = "\n" + " ---外检上传照片--- ContentAdapter2.MyClickListener==" +
                        "\n" + "PHOTO_TYPE::" + PHOTO_TYPE + "\n"
                        + "PHOTO_TYPE_huan::" + PHOTO_TYPE_huan + "\n"
                        + "TypeModel_tid::" + TypeModel_tid + "\n" +
                        "img_number:" + img_number + "\n" +
                        "img_code:" + img_code + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
            } else if (flag == 2) {
//                //跳转到图片预览界面
                if (WAIJIAN_PHOTO_PREVIEW_LISTS.get(PHOTO_TYPE) != null) {
                    Intent intent_preview = new Intent(instances, PhotoPreviewActivity.class);
                    intent_preview.putExtra("key_integer", PHOTO_TYPE);
                    intent_preview.putExtra("key", "waijian");
                    startActivity(intent_preview);
                } else {
                    if (HUANBAO_PHOTO_PREVIEW_LISTS.get(String.valueOf(TypeModel_tid)) != null) {
                        Intent intent_preview = new Intent(instances, PhotoPreviewActivity.class);
                        intent_preview.putExtra("key_integer", String.valueOf(TypeModel_tid));
                        intent_preview.putExtra("key", "huanbao");
                        startActivity(intent_preview);
                    }
                }
            }
        }
    };

//
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//            String logStr = "\n" + "外检--返回键-屏幕底部" + "\n";
//            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//
////            updateCarStatusInfor_anjian(ITEM_MIDDLE_EXIT_CODE);
//            finish();
//            return true;
//        } else {
//            return super.onKeyDown(keyCode, event);
//        }
//    }

    //上传照片
    private void getDataUploadPhoto_HuanBao(final File file, final String file_name, boolean isHide) {
        Log.e("tag", "66666667777777");
        UtilsLog.e("环保getDataUploadPhoto---url==" + SharedPreferencesUtils.getHuanBaoIP(instances) + Huanbao_UPLOAD_PHOTO);
        String DetectionCategory = "1";
        if (huanBaoModel.getDetectionCategory().equals("00")) {
            DetectionCategory = "2";
        } else {
            DetectionCategory = "1";
        }
        String carNO = "";
        if (SharedPreferencesUtils.getIsSpecialCarMode(instances)) {
            carNO = huanBaoModel.getPlateRegion() + huanBaoModel.getPlateNO() + huanBaoModel.getPlateExtra();
        } else {
            carNO = huanBaoModel.getPlateRegion() + huanBaoModel.getPlateNO() + huanBaoModel.getPlateExtra();
        }
        String str = "QueueID:" + huanBaoModel.getQueueID() + "\n" +
                "GUID:" + huanBaoModel.getGUID() + "\n" +
                "Times:" + "1" + "\n" +
                "PlatformSN:" + huanBaoModel.getPlatformSN() + "\n" +
                "SN:" + huanBaoModel.getSN() + "\n" +
                "PhotoDate:" + DateUtil.currentTime2() + "\n" +
                "PhotoType:" + img_number + "\n" +
                "Type:" + huanBaoModel.getType() + "\n" +
                "PlateNO:" + carNO + "\n" +
                "ImageType:" + img_code + "\n" +
                "DetectionCategory:" + DetectionCategory + "\n" +
                "DetectionDate:" + huanBaoModel.getDetectDate() + "\n" +
                "PlateType:" + huanBaoModel.getPlateType() + "\n" +
                "ItemCode:" + "F1" + "\n" +
                "Line:" + waijian_chedao + "\n" +
                "CarNO:" + carNO + "\n" +
                "VIN:" + huanBaoModel.getVIN() + "\n" +
                "img_number:" + img_number + "\n" +
                "img_code:" + img_code + "\n" +
                "AppearanceInspector:" + Login_name + "\n" +
                "FileType:" + "jpg" + "\n";
        UtilsLog.e("环保getDataUploadPhoto---json==" + str);

        String logStr = "\n" + "环保---外检上传照片---json==" +
                "\n" + "json::" + str + "\n" + "url:" +
                SharedPreferencesUtils.getHuanBaoIP(instances) + Huanbao_UPLOAD_PHOTO;
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
        OkGo.<String>post(SharedPreferencesUtils.getHuanBaoIP(instances) + Huanbao_UPLOAD_PHOTO).tag(instances)
//                .params("PHOTO_TYPE", PHOTO_TYPE)
                .params("ImageType", img_code)
                .params("ABC", img_code)
                //guid
                .params("QueueID", huanBaoModel.getQueueID())
                //guid
                .params("GUID", huanBaoModel.getGUID())
                //次数
                .params("Times", "1")
                //PlatformSN
                .params("PlatformSN", huanBaoModel.getPlatformSN())
                //SN
                .params("SN", huanBaoModel.getSN())
                //拍摄时间
                .params("PhotoDate", DateUtil.currentTime2())
                //照片类型-拍的哪里的照片，位置
//                .params("PhotoType", getPlatformCode(PHOTO_TYPE))
                .params("PhotoType", img_number)
                .params("ImageType2", img_code)
                .params("ImageType3", img_code)
                .params("PlateNO", carNO)
//                .params("ImageType", img_code)
                //车辆类型
                .params("Type", huanBaoModel.getType())
                //车牌号码，两个拼起来的
                .params("CarNO", carNO)
                //号牌类型
                .params("PlateType", huanBaoModel.getPlateType())
                //拍照code F1表示外检
                .params("ItemCode", "F1")
                //外检车道，检测线代号
                .params("Line", waijian_chedao)
                //车辆识别代码
                .params("VIN", huanBaoModel.getVIN())
                .params("FileType", "jpg")
//                .params("FileType", FileUtils.getExtensionName(file.getName()))
                .params("DetectionCategory", DetectionCategory)
                .params("DetectionDate", huanBaoModel.getDetectDate())
                //照片
                .params("zp", file)
                .params("AppearanceInspector", Login_name)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        if (isHide) {
//                            CommonUtils.showLoadingDialog(instances, "加载中...");
                        } else {
                            CommonUtils.showLoadingDialog(instances, "加载中...");
                        }


                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        UtilsLog.e("环保getDataUploadPhoto-result==" + result);

                        String logStr = "\n" + "环保--外检上传照片--请求成功" +
                                "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
                                Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        WAIJIAN_PHOTO_PREVIEW_LISTS.put(PHOTO_TYPE, file);
                        HUANBAO_PHOTO_PREVIEW_LISTS.put(String.valueOf(TypeModel_tid), file);
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("环保getDataUploadPhoto-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {

                                Toast.makeText(instances, "上传成功", Toast.LENGTH_LONG).show();
                                typeModel.setColor(1);
                                typeModel.setIsphoto(1);
                                typeModel.update();
                                list.set(TypeModel_Position, typeModel);
                                contentAdapter2.notifyDataSetChanged();
                            } else {
                                String logStr2 = "\n" + "环保--外检上传照片--失败" +
                                        "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
                                        Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body();
                                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr2.getBytes());
                                Toast.makeText(instances, "上传失败，请重新拍照", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            String logStr3 = "\n" + "环保--外检上传照片--失败" +
                                    "\n" + "data::" + "没有数据" + "\n" + "result:" + response.body();
                            PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr3.getBytes());
                            UtilsLog.e("getDataUploadPhoto-result==" + "没有数据");
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        HUANBAO_PHOTO_PREVIEW_LISTS.put(String.valueOf(TypeModel_tid), file);
                        UtilsLog.e("环保getDataUploadPhoto-onError==" + response.body());
                        UtilsLog.e("环保getDataUploadPhoto-onError==" + response.getException());
                        String logStr = "\n" + "环保--外检上传照片-onError-失败" +
                                "\n" + "URL::" + SharedPreferencesUtils.getHuanBaoIP(instances) +
                                Huanbao_UPLOAD_PHOTO + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message();
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        CommonUtils.hideLoadingDialog(instances);

                        Toast.makeText(instances, "上传照片失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }
}
